import { message, Table } from 'antd';
import Cls from 'classnames';
import { useContext, useEffect, useMemo } from 'react';
import { useAssetTableColumn, returnAssetTableColumn } from '../mconfig/AssetTablecolumn';
import { LYflowBusinessType } from '../common/FormatUse';
import { AcquisitionManageContext, IAcquisitionActionEnum } from '../mconfig';
import { getPosIDs, getTenantID, getUserID } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { formatDecimalFou, formatDecimal } from '@/pages/AssetManage/Acommon';

/** 领用/退库 表单第二项-资产列表 */
export const AssetTableView: React.FC<any> = ({
  openAssetModalFun,
  pageType,
  loadMapInfo,
  mapLoading,
  queryType,
  storeTreeList,
  getStorageLoading,
  editState,
  finish,
  changeEditAssetId,
  handleEditSave,
  detailInfo,
}) => {
  const { assetList, acquisitionDispatch } = useContext(AcquisitionManageContext);

  /** 改变选择的资产列表的存储仓库 */
  const changeAssetItemStore = (index: number, node: any) => {
    let arr = JSON.parse(JSON.stringify(assetList));
    arr[index].assetStoreId = node.id;
    arr[index].assetStoreState = node.storeState;
    arr[index].assetStoreName = node.storeName;
    // 存储到仓库
    acquisitionDispatch({
      type: IAcquisitionActionEnum.SELECT_ASSET,
      payload: [...arr],
    });
  };

  /** 取消选择的资产 */
  const delSelectRow = (record) => {
    if (editState && assetList.length == 1) {
      message.error('至少保留一条资产!');
      return;
    }

    const arr = assetList.filter((item) => {
      return item.id !== record.id;
    });
    acquisitionDispatch({
      type: IAcquisitionActionEnum.CANCEL_ASSET,
      payload: arr,
    });
    const taskType: string = LYflowBusinessType();
    const taskHandInfo: Record<string, any> = detailInfo?.paramObject?.[taskType];
    /** 复核中 修改报错 */
    if (
      (detailInfo?.queryType == '1' || detailInfo?.queryType == '3') &&
      taskHandInfo &&
      taskHandInfo?.mactivitiTaskList?.length > 0 &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneeID == getUserID() &&
      detailInfo?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1006`
    )
      handleEditSave(arr);
  };

  /** 表格行配置 */
  const getTable: any = useMemo(() => {
    if (queryType == '1' || queryType == '3') {
      return useAssetTableColumn({
        openAssetModalFun,
        delSelectRow,
        pageType,
        loadMapInfo,
        mapLoading,
        queryType: 1,
        storeTreeList,
        getStorageLoading,
        changeAssetItemStore,
        editState,
        changeEditAssetId,
        finish,
      });
    } else {
      return returnAssetTableColumn({
        openAssetModalFun,
        delSelectRow,
        pageType,
        loadMapInfo,
        mapLoading,
        queryType: 2,
        storeTreeList,
        getStorageLoading,
        changeAssetItemStore,
        editState,
        changeEditAssetId,
        finish,
      });
    }
  }, [assetList, queryType, pageType, editState, finish, loadMapInfo, storeTreeList]);

  // 总价
  const allPrice = useMemo(() => {
    // 判断标识
    const f = pageType == 'detail';

    let val = 0;
    if (assetList?.length) {
      assetList?.forEach((item) => {
        if (f) {
          val += (Number(item?.expectNum) + Number(item?.quantityOrArea)) * Number(item?.totalValue);
        } else {
          val +=
            (Number(item?.residueNum) || Number(item?.expectNum) + Number(item?.quantityOrArea) || Number(item?.quantityOrArea)) * Number(item?.totalValue);
        }
      });
    }
    return val;
  }, [assetList, pageType]);

  return (
    <>
      <div className={Cls('list-table', 'descriptionsType-tableSty')}>
        <Table columns={getTable} bordered size="small" dataSource={assetList} scroll={{ x: 1200, y: '' }} pagination={false} rowKey={(res) => res?.id} />
        <div style={{ textAlign: 'right', marginBottom: '10px' }}>合计：{formatDecimal(allPrice) || '0.0000'}</div>
      </div>
    </>
  );
};
